package com.mycat.manager.controller.auth;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.mycat.common.entity.InvokeResult;
import com.mycat.dao.dto.auth.AdminAddRoleDTO;
import com.mycat.dao.dto.common.CommonDTO;
import com.mycat.dao.dto.common.PermissionDTO;
import com.mycat.dao.entity.auth.Admin;
import com.mycat.manager.content.PasswordHelper;
import com.mycat.service.auth.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 *  后台权限模块页面跳转
 * @author Roger
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    /**
     *  进入用户管理
     */
    @RequestMapping(method = RequestMethod.GET)
    @RequiresPermissions("admin:view")
    public String toList() {
        return "auth/admin";
    }

    /**
     * 验证当前用户时候拥有访问权限
     */
    @RequestMapping(value = "/hasPermission",method = RequestMethod.POST)
    public ResponseEntity<InvokeResult<Boolean[]>> verifyHasPermission(@RequestBody PermissionDTO permissions){
        InvokeResult invokeResult = null;
        try {
            Subject subject = SecurityUtils.getSubject();
            if (null != permissions && null != permissions.getPermission() && permissions.getPermission().length > 0) {
                int length = permissions.getPermission().length;
                Boolean[] hasPermission = new Boolean[length];
                for (int i = 0;i< length;i++){
                    hasPermission[i] = subject.isPermitted(permissions.getPermission()[i]);
                }
                invokeResult = InvokeResult.success(hasPermission);
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取分页数据
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     */
    @RequestMapping(value = "/{pageNum}/{pageSize}", method = RequestMethod.GET)
    @RequiresPermissions("admin:view")
    @ResponseBody
    public ResponseEntity<InvokeResult<PageInfo<Admin>>> page(@PathVariable int pageNum, @PathVariable int pageSize) {
        InvokeResult invokeResult = null;
        try {
            Page<Admin> page = new Page<Admin>() {{
                this.setPageNum(pageNum);
                this.setPageSize(pageSize);
            }};
            PageInfo<Admin> pageInfo = adminService.findAdmins(page);
            if (null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
                invokeResult = InvokeResult.success(pageInfo);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取单个对象
     *
     * @param id Id
     */
    @RequiresPermissions("admin:view")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult> getAdmin(@PathVariable Integer id) {
        InvokeResult invokeResult = null;
        try {
            if (null != id) {
                Admin admin = adminService.findAdmin(new Admin(id));
                invokeResult = InvokeResult.success(admin);
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 删除对象
     *
     * @param commonDTO 删除数据DTO
     */
    @RequiresPermissions("admin:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<InvokeResult> delete(@RequestBody CommonDTO commonDTO) {
        InvokeResult invokeResult = null;
        try {
            if (null != commonDTO && null != commonDTO.getIds() && commonDTO.getIds().length > 0) {
                adminService.delAdmin(commonDTO.getIds());
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 新增数据
     *
     * @param admin 新增对象
     */
    @RequiresPermissions("admin:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> add(Admin admin) {
        InvokeResult invokeResult = null;
        try {
            if (null != admin && !StringUtils.isEmpty(admin.getUserName()) && null != admin.getPswd()) {
                admin.setSalt(PasswordHelper.getSalt());
                admin.setPswd(PasswordHelper.encryptPwd(admin.getPswd(),admin.getSalt()));
                adminService.addAdmin(admin);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 修改数据
     *
     * @param admin 修改对象
     */
    @RequiresPermissions("admin:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> edit(Admin admin) {
        InvokeResult invokeResult = null;
        try {
            if (null != admin && null != admin.getId()) {
                if(!StringUtils.isEmpty(admin.getPswd())){
                    admin.setSalt(PasswordHelper.getSalt());
                    admin.setPswd(PasswordHelper.encryptPwd(admin.getPswd(),admin.getSalt()));
                }
                adminService.updateAdmin(admin);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 根据用户Id获取用户已经分配角色
     * @param adminId 用户ID
     */
    @RequiresPermissions("admin:addRole")
    @RequestMapping(value = "/getAdminRole/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult<Admin>> getAdminRole(@PathVariable Integer adminId) {
        InvokeResult invokeResult = null;
        try {
            if (null != adminId) {
                Admin admin = adminService.findAdminRole(new Admin(adminId));
                invokeResult = InvokeResult.success(admin);
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 用户分配角色
     * @param adminAddRoleDTO 参数集合
     */
    @RequiresPermissions("admin:addRole")
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> addRole(@RequestBody AdminAddRoleDTO adminAddRoleDTO) {
        InvokeResult invokeResult = null;
        try {
            if (null != adminAddRoleDTO && null != adminAddRoleDTO.getAdminId()) {
                adminService.addAdminRole(adminAddRoleDTO.getRoleIds(), adminAddRoleDTO.getAdminId());
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }
}
